package cn.wanda.bi.sunshine.platform.server.utils;

import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Created by wangfupeng1 on 2017-4-29.
 */
public class Utils {

    public static <T> T valueOf(T value, T defaultValue) {
        return Optional.ofNullable(value).orElse(defaultValue);
    }

    public static String listToString(List<String> list) {
        return list.stream().collect(Collectors.joining(","));
    }

    public static final Long day = 86400000L;

    public static String where(Long begin, Long end) {
        return where(begin, end, "");
    }

    public static String where(Long begin, Long end, String field) {
        end = end + day;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String beginTime = dateFormat.format(new Date(begin));
        String endTime = dateFormat.format(new Date(end));

        if(StringUtils.isEmpty(field))
            return "(((begin_time BETWEEN '" + beginTime + "' AND '" + endTime + "') or (end_time BETWEEN '" + beginTime + "' AND '" + endTime + "')) " +
                    " or ('" + beginTime + "' BETWEEN begin_time AND end_time))";
        else
            return String.format("(" + field + " BETWEEN '%s' AND '%s')", beginTime, endTime);
    }
}
